package cn.oi.klittle.era.https;

import java.security.SecureRandom;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import cn.oi.klittle.era.utils.KLoggerUtils;

public class KSSL {
    ///是否忽略https证书，默认忽略。
    public static boolean isHandleSSLHandshake = true;
    public static TrustManager[] trustAllCerts;
    public static SSLContext ssl;
    public static HostnameVerifier hostnameVerifier;

    ///判断是否为https
    public static boolean isHttps(String url) {
        if (url != null && url.contains("https")) {
            return true;
        }
        return false;
    }

    ///忽略https的证书校验
    public static void handleSSLHandshake(HttpsURLConnection https) {
        if (isHandleSSLHandshake) {
            try {
                if (trustAllCerts == null) {
                    trustAllCerts = new TrustManager[]{new X509TrustManager() {
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[0];
                        }

                        @Override
                        public void checkClientTrusted(X509Certificate[] certs, String authType) {
                        }

                        @Override
                        public void checkServerTrusted(X509Certificate[] certs, String authType) {
                        }
                    }};
                    ssl = SSLContext.getInstance("TLS");
                    // trustAllCerts信任所有的证书
                    ssl.init(null, trustAllCerts, new SecureRandom());
                    hostnameVerifier = new HostnameVerifier() {
                        @Override
                        public boolean verify(String hostname, SSLSession session) {
                            return true;//fixme 忽略证书
                        }
                    };
                    HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
                    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                        @Override
                        public boolean verify(String hostname, SSLSession session) {
                            return true;
                        }
                    });
                }
                if (https != null && hostnameVerifier != null) {
                    https.setDefaultHostnameVerifier(hostnameVerifier);
                }
            } catch (Exception ignored) {
                KLoggerUtils.INSTANCE.e("Https SSL忽略证书异常:" + ignored.getMessage());
            }
        }
    }
}
